package com.example.xunua_zhinengjiaotong;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.xunua_zhinengjiaotong.utils.HttpUtil;
import com.example.xunua_zhinengjiaotong.utils.MyApp;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

public class StopCarActivity extends AppCompatActivity implements View.OnClickListener {
    private ImageView img_back;
    private RelativeLayout stop_state,stop_Message;
    private AlertDialog.Builder builder;
    private int choice=0;
    private TextView tv_xiaoshi,tv_feilv,tv_chewei,tv_xsc;
    private RelativeLayout rl,rl_gone,rl_heimingdan;
    private EditText et_feilv;
    private ImageButton btn_set;
    private HttpUtil util=new HttpUtil();
    private MyApp myApp;

    Handler handler=new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0) {
                String[] park= (String[]) msg.obj;
                tv_feilv.setText(park[0]);
                tv_chewei.setText(park[1]);
            } else if (msg.what == 1) {
                Toast.makeText(myApp, "设置成功", Toast.LENGTH_SHORT).show();
                if (tv_xiaoshi.getText().toString().equals("小时")) {
                    getflcw("Time");
                }else if (tv_xiaoshi.getText().toString().equals("状态")){
                    getflcw("Count");
                }
            } else if (msg.what == 2) {
                Toast.makeText(myApp, "设置失败，请输入1-100的数字", Toast.LENGTH_SHORT).show();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_stop_car);
        initView();
        getflcw("Time");
    }
    private void initView() {
        myApp= (MyApp) getApplication();
        img_back=findViewById(R.id.stop_img_back);
        img_back.setOnClickListener(this);
        stop_state =findViewById(R.id.stop_state);
        stop_state.setOnClickListener(this);
        rl=findViewById(R.id.stop_rl);
        rl.setOnClickListener(this);
        rl_gone=findViewById(R.id.stop_rl_gone);
        rl_heimingdan=findViewById(R.id.stop_heimingdan);
        rl_heimingdan.setOnClickListener(this);
        stop_Message=findViewById(R.id.stopcar_rlMessage);
        stop_Message.setOnClickListener(this);
        tv_xiaoshi=findViewById(R.id.stop_tv_xiaoshi);
        et_feilv=findViewById(R.id.stop_et_feilv);
        btn_set=findViewById(R.id.stop_ib_set);
        btn_set.setOnClickListener(this);
        tv_feilv=findViewById(R.id.stop_tv_feilv);
        tv_chewei=findViewById(R.id.stop_tv_chewei);
        tv_xsc=findViewById(R.id.stop_tv_xsc);
    }

    /**
     * 获取费率和车位
     */
    private void getflcw(final String RateType){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    JSONObject getParkRate = util.connectServer("{\"RateType\":\""+RateType+"\"}", myApp, "GetParkRate");
                    String parkRateString = getParkRate.getString("Money");
                    JSONObject getParkFree = util.connectServer("{}", myApp, "GetParkFree");
                    String parkFreeId = getParkFree.getString("ParkFreeId");
                    String[] park={parkRateString,parkFreeId};
                    Message message = new Message();
                    message.what=0;
                    message.obj=park;
                    handler.sendMessage(message);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.stop_img_back:
                finish();
                break;
            case R.id.stop_state:
                String trim = tv_xiaoshi.getText().toString().trim();
                showAlert(trim);
                break;
            case R.id.stop_rl:
                if (rl_gone.getVisibility()==View.GONE){
                    rl_gone.setVisibility(View.VISIBLE);
                }else {
                    rl_gone.setVisibility(View.GONE);
                }
                break;
            case R.id.stop_heimingdan:
                showmultisAlert();
                break;
            case R.id.stopcar_rlMessage:
                startActivity(new Intent(StopCarActivity.this,StopCarMessageActivity.class));
                break;
            case R.id.stop_ib_set:
                String typeName=null;
                if (choice == 0) {
                    //小时
                    typeName="Hour";
                } else if (choice == 1) {
                    //状态
                    typeName="Count";
                }
                String money=et_feilv.getText().toString().trim();
                if (money.isEmpty()||money.equals("0")) {
                    Toast.makeText(myApp, "请输入正确的费率", Toast.LENGTH_SHORT).show();
                    return;
                }
                setfeilv(typeName,money);
                break;
        }
    }

    private void setfeilv(final String RateType, final String Money){
        if (RateType == null) {
            return;
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    JSONObject setParkRate = util.connectServer("{\"RateType\":\"" + RateType + "\",\"Money\":" + Money + "}", myApp, "SetParkRate");
                    String result = setParkRate.getString("result");
                    if(result.equals("ok")){
                        handler.sendEmptyMessage(1);
                    }
                }catch (Exception e){
                    handler.sendEmptyMessage(2);
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 单选对话框
     */
    private void showAlert(String s){
        final CharSequence[] charSequences = {"小时","状态"};
        int checkedItem=0;
        for (int i = 0; i <charSequences.length; i++) {
            if (charSequences[i].equals(s)){
                checkedItem=i;
            }
        }
        builder=new AlertDialog.Builder(StopCarActivity.this);
        builder.setIcon(R.mipmap.buslogo)
                .setTitle("ETC费率设置")
                .setCancelable(false)
                .setSingleChoiceItems(charSequences, checkedItem, new DialogInterface.OnClickListener() {
                    //单选按钮的点击事件
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //which  被选中的item的position索引
                        choice=which;
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    //确定按钮的点击事件
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (choice != -1) {
                            tv_xiaoshi.setText(charSequences[choice].toString()+"");
                            if (choice == 0) {
                                //小时
                                getflcw("Time");
                                tv_xsc.setText("/小时");
                            } else if (choice == 1) {
                                //状态
                                getflcw("Count");
                                tv_xsc.setText("/次");
                            }
                        }
                    }
                });
        builder.create().show();
    }

    /**
     * 多选框
     */
    private String[]items={"一号小车","二号小车","三号小车","四号小车"};
    private boolean[]ischeckeds={false,false,false,false};
    private void showmultisAlert(){
        builder=new AlertDialog.Builder(StopCarActivity.this);
        builder.setIcon(R.mipmap.buslogo)
                .setTitle("黑名单设置")
                .setCancelable(false)
                .setMultiChoiceItems(items, ischeckeds, new DialogInterface.OnMultiChoiceClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                        //which 操作的item
                        ischeckeds[which]=isChecked;
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String s="";
                        for (int i = 0; i < 4; i++) {
                            if (ischeckeds[i]){
                                s+=items[i]+"   ";
                            }
                        }
//                        Toast.makeText(StopCarActivity.this, "选中的小车："+s, Toast.LENGTH_SHORT).show();
                        //服务器这个api接口和ETC黑名单下发一样没有作用 找不到此接口，节省时间不写此功能了。
                        Toast.makeText(myApp, "未找到SetParkBlackList接口", Toast.LENGTH_SHORT).show();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
        builder.create().show();
    }
    @Override
    public void onBackPressed() {
        // super.onBackPressed();
    }
}
